<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<h1>分段上传华为云Demo</h1>
<div>
    <form id="uploadForm" enctype="multipart/form-data">
        <input type="file" id="fileInput" name="file">
        <button type="submit">上传文件</button>
    </form>
</div>
</body>
</html>
<script src="../../assets/libs/jquery/dist/jquery.js"></script>
<script>
    //分段上传
    $(document).ready(function() {
        // 监听表单提交事件
        $('#uploadForm').submit(function(event) {
            event.preventDefault();

            // 获取选定的文件
            let file = $('#fileInput')[0].files[0];
            // 获取文件名
            let file_name = file.name;
            let partSize = 1 * 1024 * 1024; // 分段大小，这里设置为5MB

            //获取分片上传初始化信息
            // 调用函数并处理返回结果
            var init_data = getUploadConfig(file_name);
            if (!init_data){
                alert('初始化错误')
                return false
            }
            var path =init_data.path//文件合并后在obs上的保存路径
            var fileId =init_data.upload_id//切片上传的

            // 数据切片
            var chunks = fileSlice(file,partSize);

            // 发送分割数据段
            uploadPart(fileId, chunks, path,0,[]);

        });

        //获取分段上传配置信息
        function getUploadConfig(file_name){
            var res_data;
            $.ajax({
                url : 'test/initiateMultipartUpload',
                type : "post",
                data : {
                    'file_name':file_name
                },
                async : false,
                success : function(res) {
                    if (res.code){
                        res_data = res.data
                    }
                }
            });
            return res_data;
        }

        //数据切片
        function fileSlice(file, chunkSize = 1024*1024*0.2){
            // 1.初始化数据
            var totalSize = file.size;
            var start = 0;
            var end = start + chunkSize;
            var chunks = [];
            // 2.使用bolb提供的slice方法切片
            while(start < totalSize){
                var chunk = file.slice(start, end);
                chunks.push(chunk);
                start = end;
                end += chunkSize;
            }
            // 3.返回切片组chunk[]
            return chunks;
        }

        //执行逐个上传
        function uploadPart(upload_id, chunks, path,index = 0,parts = []) {
            if (index >= chunks.length) {
                // 所有部分上传完成
                makeFileIntegration(upload_id, chunks.length, parts, path);
                return;
            }

            var chunk = chunks[index];
            var formData = new FormData();
            formData.append('upload_id', upload_id);
            formData.append('chunk', chunk);
            formData.append('path', path);

            let part_number = index + 1
            formData.append('part_number', part_number);

            $.ajax({
                type: "POST",
                url: 'test/uploadPart',
                data: formData,
                contentType: false,
                processData: false,
                success: function (done) {
                    if (done.code) {
                        parts.push(done.data);
                        console.log(done, ' 已完成');
                        uploadPart(upload_id, chunks, path,part_number,parts); // 递归调用上传下一个部分
                    }
                }
            });
        }

        //通知整合方法
        function makeFileIntegration(upload_id, size,parts,path){
            // 通知已传输完成
            $.ajax({
                url : 'test/completeMultipartUpload',
                type : "post",
                data : {
                    'upload_id':upload_id,
                    'parts':parts,
                    'path':path,
                },
                async : false,
                success : function(res) {
                    alert(666);
                    console.log(res.data)
                    if (res.code){
                        res_data = res.data
                    }
                }
            });
        }
    });
</script>